import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import * as api from './api';
/* =======================获取详情================================== */
export const GET_BRANDS_BEGIN = 'GET_BRANDS_BEGIN';
export const GET_BRANDS_SUCCESS = 'GET_BRANDS_SUCCESS';
export const GET_BRANDS_FAIL = 'GET_BRANDS_FAIL';
export const getBrandBegin = () => ({
    type: GET_BRANDS_BEGIN
});
export const getBrandSuccess = data => ({
    type: GET_BRANDS_SUCCESS,
    data
});
export const getBrandFail = () => ({
    type: GET_BRANDS_FAIL,
});

export const getBrands = condition => dispatch => {
    dispatch(getBrandBegin());
    return api.getBrands(condition).then(res => {
        if(res.ok)
            dispatch(getBrandSuccess(res.data));
        else
            dispatch(getBrandFail());
        return res.ok;
    });
};

//*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = data => ({
    type: GET_INIT_SUCCESS,
    data,
});
export const getInitDataFail = () => ({
    type: GET_INIT_FAIL,
});
export const getInitData = (code = PAGE_CODE) => dispatch => {
    const init = dispatch(getBrands());
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    const types = api.initQuery().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        else
            dispatch(getInitDataFail());
        return res.ok;
    });
    return Promise.all([init, permissions, types]).then(values => values[0] && values[1] && values[2]);
};
/*==============================查询列表================================= */

export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = () => ({
    type: GET_LIST_FAIL,
}); //获取列表

export const getList = condition => dispatch => {
    dispatch(getListBegin());
    const {dealerCode, dealerName, ...props} = condition;
    return api.getList(props).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
}; //按钮搜索

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    return dispatch(getList(condition));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    return dispatch(getList(condition));
};

/*==============================查询action================================= */
//修改查询条件

export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});

/*==========================修改新增编辑页数据================================= */
export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';

export const saveSubmitCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});
/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getDetail(id).then(res => {
        if(res.ok)
            dispatch(getDetailSuccess(res.data));
        else
            dispatch(getDetailFail());
        return res.ok;
    });
};

/*==============================清除数据================================= */
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});
export const onClickAddSubmit = () => (dispatch, getState) => {
    const {
        id,
        rowVersion,
        dealerId,
        details = [],
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    return id ? api.editInfo(id, {
        rowVersion,
        details: details.map(item => ({
            packingListId: item.packingListId,
            rowVersion: item.rowVersion
        }))
    }) : api.addInfo({
        dealerId,
        details: details.map(item => ({
            packingListId: item.packingListId,
            rowVersion: item.rowVersion
        }))
    });
};

export const onClickUpdate = id => (dispatch, getState) => {
    const {
        containerNo,
        cabinetType,
        rowVersion,
        attachments = [],
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    return api.updateInfo(id, {
        attachments,
        containerNo,
        cabinetType,
        rowVersion,
    });
};

export const SELECT_DATA = 'SELECT_DATA';
export const selectData = data => ({
    type: SELECT_DATA,
    data
});

export const SELECT_DEALER_QUERY = 'SELECT_DEALER_QUERY';
export const selectDealer = data => ({
    type: SELECT_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});

export const selectCountry = data => dispatch => dispatch(selectData({
    dealerId: data.id,
    dealerCode: data.code,
    dealerName: data.name,
    country: data.countryName,
}));

export const SELECT_DETAILS = 'SELECT_DETAILS';
export const selectDetails = data => ({
    type: SELECT_DETAILS,
    data
});

export const DELETE_DETAIL = 'DELETE_DETAIL';
export const deleteDetail = id => ({
    type: DELETE_DETAIL,
    id
});
export const DELETE_ALL_DETAIL = 'DELETE_ALL_DETAIL';
export const deleteAllDetail = () => ({
    type: DELETE_ALL_DETAIL
});

export const UPDATE_ATTACHMENTS = 'UPDATE_ATTACHMENTS';
export const updateAttachments = data => ({
    type: UPDATE_ATTACHMENTS,
    data: {
        fileId: data.id,
        fileName: data.fileName
    }
});

export const REMOVE_ATTACHMENTS = 'REMOVE_ATTACHMENTS';
export const removeAttachments = id => ({
    type: REMOVE_ATTACHMENTS,
    id
});

export const selectPacking = data => dispatch => {
    const conditions = data.map(item => ({
        packingListId: item.id,
        packingCode: item.code,
        packingType: item.packingType,
        container: item.container,
        length: item.length,
        width: item.width,
        height: item.height,
        volume: item.volume,
        netWeight: item.netWeight,
        grossWeight: item.grossWeight,
        rowVersion: item.rowVersion,
        packingListDetails: [],
        pickingListCodes: item.pickingListCodes
    }));
    dispatch(selectDetails(conditions));
};


export const SET_PACKING_DETAIL = 'SET_PACKING_DETAIL';
export const setPackingDetail = (id, data) => ({
    type: SET_PACKING_DETAIL,
    id,
    data
});
export const getPackingDetail = id => dispatch => api.getPackingDetail(id).then(res => {
    if(res.ok) {
        const {details = []} = res.data;
        const rowObj = {};
        const sortedData = details.sort((a, b) => {
            if(a.partSaleOrderCode > b.partSaleOrderCode) return 1;
            else if(a.partSaleOrderCode < b.partSaleOrderCode) return -1;
            return 0;
        });
        const newDetails = sortedData.map(item => {
            if(rowObj[item.partSaleOrderCode])
                return {
                    ...item,
                    rowSpan: 0,
                };
            const count = sortedData.filter(d => d.partSaleOrderCode === item.partSaleOrderCode);
            rowObj[item.partSaleOrderCode] = true;
            return {
                ...item,
                rowSpan: count.length
            };
        });
        dispatch(setPackingDetail(id, newDetails));
    }
    return res.ok;
});
